class Solution {
public:
    vector<int> findXSum(vector<int>& nums, int k, int x) {
        unordered_map<int, int> hash;
        for (int i = 0; i < k; i++) hash[nums[i]]++;
        vector<int> res;
        set<pair<int, int>, greater<pair<int, int>>> sp;
        for (auto& [x, y] : hash) sp.insert({ y, x });
        int restmp = 0;
        int tmpx = 0;
        auto it = sp.begin();
        while (tmpx < x && tmpx < hash.size()) {
            restmp += it->first * it->second;
            it++;
            tmpx++;
        }
        res.push_back(restmp);

        for (int i = k; i < nums.size(); i++) {
            int a = hash[nums[i]], b = hash[nums[i - k]];
            if (a) sp.erase({ a, nums[i] });
            if (b) sp.erase({ b, nums[i - k] });
            hash[nums[i]]++, hash[nums[i - k]]--;
            sp.insert({ hash[nums[i]], nums[i] });
            sp.insert({ hash[nums[i - k]], nums[i - k] });
            tmpx = 0;
            it = sp.begin();
            restmp = 0;
            while (tmpx < x && tmpx < hash.size()) {
                restmp += it->first * it->second;
                it++;
                tmpx++;
            }
            res.push_back(restmp);
        }
        return res;
    }
};